package org.alex.nettychat.netty.custom.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.alex.nettychat.netty.custom.protocol.PacketCode;

/**
 * @author : alex
 */
public class Spliter extends LengthFieldBasedFrameDecoder {

    // 偏移量
    private static final int LENGTH_FIELD_OFFSET = 7;

    // 长度域
    private static final int LENGTH_FIELD_LENGTH = 4;

    public Spliter() {
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);

    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        // 屏蔽分本协议客户端
        if (in.getInt(in.readerIndex()) != PacketCode.MAGIC_NUMBER) {
            ctx.channel().close();
            return null;
        }

        return super.decode(ctx, in);
    }
}
